import { ConfigProvider, Pagination, Row, Table } from 'antd';
import React, { forwardRef, Ref, useEffect, useImperativeHandle, useState } from 'react';
import zhCN from 'antd/lib/locale/zh_CN';
import { request, requestOptions } from '../../../utils/request';
import { useLocation, useNavigate } from 'react-router-dom';
import queryString from 'query-string';
import { v4 as uuidv4 } from 'uuid';

type columnItem = {
  key: string;
  title: string;
  dataIndex: string;
  [props: string]: any;
}

type TableRequestType = {
  url?: string,
  options?: requestOptions,
}

interface TableListProps {
  columns: Array<columnItem>,
  ref?: Ref<any>,
  requiredParams?: any,
  hidePagination?: boolean,
  requestOptions?: TableRequestType
  getDataSource?: (data: any) => void,
  expandedRowKeys?: Array<string>,
  expandedRowRender?: (record: any) => React.ReactNode,
  onExpand?: (expanded: boolean, record: any) => void,
  rowSelection?: any,

  [propsName: string]: any
}

interface modalProps extends React.FC<TableListProps> {
}

// @ts-ignore
export const TableList: modalProps = forwardRef(({
                                                   columns,
                                                   requiredParams,
                                                   hidePagination = false,
                                                   requestOptions,
                                                   getDataSource,
                                                   expandedRowKeys,
                                                   expandedRowRender,
                                                   onExpand,
                                                   rowSelection,
                                                   ...restProps
                                                 }, ref) => {
  const location = useLocation();
  const urlData = queryString.parse(location.search);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [totalCount, setTotalCount] = useState<number>(0);
  const [query, setQuery] = useState(urlData);
  const [pageNo, setPageNo] = useState<number>(urlData.pageNo ? Number(urlData.pageNo) : 1);
  const [pageSize, setPageSize] = useState<number>(urlData.pageSize ? Number(urlData.pageSize) : 10);
  const navigate = useNavigate();


  useEffect(() => {
    requestData(pageNo, pageSize);
  }, []);

  useImperativeHandle(ref, () => ({
    requestData
  }));

  const requestData = async (page?: number, size?: number) => {
    if (!requestOptions?.url) return;

    let params = {
      ...query,
      pageNo: page,
      pageSize: size
    };
    const data = await request(requestOptions.url, {
      ...requestOptions.options,
      params: {
        ...params,
        ...requestOptions.options?.data
      },
      data: {
        ...params,
        ...requestOptions.options?.data
      }
    });
    setDataSource(data.list.map(item => ({ ...item, key: item.id || uuidv4() })));
    setTotalCount(data.totalCount);
    getDataSource && getDataSource(data);
    navigate(location.pathname + '?' + queryString.stringify(params));
  };


  return (
    <div>
      <ConfigProvider
        locale={zhCN}
      >
        <Table
          ref={ref}
          columns={columns}
          dataSource={dataSource}
          expandable={{
            //expandedRowKeys: expandedRowKeys ? expandedRowKeys : [],
            expandedRowRender: expandedRowRender,
            onExpand: onExpand,
          }}
          pagination={!hidePagination ? {
            size: 'small',
            total: totalCount,
            showQuickJumper: true,
            onChange: (page: number, size: number) => {
              setPageNo(page);
              setPageSize(size);
              requestData(page, size);
            },
            current: pageNo,
            showSizeChanger: true,
            pageSizeOptions: ['10', '25', '50', '75', '100'],
            pageSize: pageSize,
            showTotal: () => <span>共&nbsp;{totalCount}&nbsp;条</span>
          } as any : false}
          rowSelection={rowSelection && rowSelection}
          {...restProps}
        />
      </ConfigProvider>
    </div>
  );
});